package com.sendi.system.util.common;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/*
 * 检查用户是否登录，防止未登录就使用系统资源
 * 注意配置该过滤器时，需要放在structs2的拦截器之前
 */
public class LoginFilter implements Filter {

	/*
	 * 通过传入默认初始化参数决定拦截与否
	 */
	public boolean islogfilter=false;
	public void destroy() {
	 

	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain arg2) throws IOException, ServletException {
		
		 if(islogfilter)
		 {
			 HttpServletRequest req=(HttpServletRequest)request;
			 HttpServletResponse rep=(HttpServletResponse)response;
			 String ctx=req.getContextPath();
			 String uri=req.getRequestURI();
			 String userName = null;
			 if(req.getSession().getAttribute("username") != null){
				 userName = req.getSession().getAttribute("username").toString();
			 }
		     boolean isdvalidate=false;
		     if(uri.equals(ctx+"/")||uri.equals(ctx+"/index.jsp")||uri.equals(ctx+"/login.do")||uri.equals(ctx+"/login.jsp")||uri.equals(ctx+"/system/modipwd.jsp")||uri.equals(ctx+"/sendisystem/excuteModifyusersql.do"))
		     {
		    	 isdvalidate=true;
		     }
		     else
		     {
		    	 if(req.getSession().getAttribute("username")!=null&&req.getSession().getAttribute("username").toString().length()>0)
		    	 {
		    		 isdvalidate=true;
		    	 }
		     }
		     
		   
		     if(isdvalidate)
		     {
		    	 arg2.doFilter(request, response);
		     }
		     else
		     {
		    	 
		    	 rep.sendRedirect(ctx+"/index.jsp");
		     }
		 	 System.out.println("userName:"+userName+",Uri:"+uri);
		 }
		 else
		 {
			 arg2.doFilter(request, response);
		 }

	}

	public void init(FilterConfig arg0) throws ServletException {
		String logfilter=arg0.getInitParameter("logfilter");  //取值为off,on
		if(logfilter!=null&&logfilter.equalsIgnoreCase("on"))
		{
			islogfilter=true;
		}

	}
	
	private void logBehaviour(String userName,String reqUri){
		
	}


}
